# -*- coding: utf-8 -*-
"""
MySQL数据库字典导出工具主程序
"""
import sys
import os
from PyQt5.QtWidgets import QApplication, QMessageBox, QSplashScreen
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtGui import QPixmap, QFont

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from ui.main_window import MainWindow
from utils.logger import logger
from utils.error_handler import ErrorHandler
from utils.data_migration import data_migration
from config import APP_NAME, APP_VERSION

class MySQLDictExporterApp:
    """MySQL数据库字典导出工具应用程序"""
    
    def __init__(self):
        self.app = None
        self.main_window = None
        self.error_handler = None
    
    def setup_application(self):
        """设置应用程序"""
        # 运行数据迁移
        try:
            data_migration.run_migration()
        except Exception as e:
            print(f"数据迁移失败: {e}")
        
        # 创建QApplication
        self.app = QApplication(sys.argv)
        self.app.setApplicationName(APP_NAME)
        self.app.setApplicationVersion(APP_VERSION)
        self.app.setOrganizationName("MySQL Dict Exporter")
        
        # 设置应用程序字体
        font = QFont("Microsoft YaHei", 9)
        self.app.setFont(font)
        
        # 创建错误处理器
        self.error_handler = ErrorHandler()
        
        # 设置全局异常处理
        sys.excepthook = self.handle_exception
    
    def show_splash_screen(self):
        """显示启动画面"""
        try:
            # 创建启动画面
            splash_pix = QPixmap(400, 300)
            splash_pix.fill(Qt.white)
            
            splash = QSplashScreen(splash_pix)
            splash.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.SplashScreen)
            splash.show()
            
            # 显示启动信息
            splash.showMessage(
                f"{APP_NAME}\n版本: {APP_VERSION}\n正在启动...",
                Qt.AlignCenter | Qt.AlignBottom,
                Qt.black
            )
            
            self.app.processEvents()
            
            # 延迟关闭启动画面
            QTimer.singleShot(2000, splash.close)
            
            return splash
            
        except Exception as e:
            logger.error(f"显示启动画面失败: {e}")
            return None
    
    def create_main_window(self):
        """创建主窗口"""
        try:
            self.main_window = MainWindow()
            self.main_window.show()
            logger.info("主窗口创建成功")
        except Exception as e:
            logger.critical(f"创建主窗口失败: {e}")
            raise
    
    def handle_exception(self, exc_type, exc_value, exc_traceback):
        """处理未捕获的异常"""
        if issubclass(exc_type, KeyboardInterrupt):
            # 允许Ctrl+C中断
            sys.__excepthook__(exc_type, exc_value, exc_traceback)
            return
        
        # 记录异常
        logger.critical(f"未捕获的异常: {exc_type.__name__}: {exc_value}")
        logger.log_exception("异常详情:")
        
        # 显示错误消息
        if self.app:
            QMessageBox.critical(
                None,
                "程序错误",
                f"程序发生未处理的错误:\n{exc_type.__name__}: {exc_value}\n\n请查看日志文件获取详细信息。"
            )
    
    def run(self):
        """运行应用程序"""
        try:
            # 设置应用程序
            self.setup_application()
            
            # 显示启动画面
            splash = self.show_splash_screen()
            
            # 创建主窗口
            self.create_main_window()
            
            # 关闭启动画面
            if splash:
                splash.finish(self.main_window)
            
            # 记录启动成功
            logger.info(f"{APP_NAME} v{APP_VERSION} 启动成功")
            
            # 运行应用程序
            return self.app.exec_()
            
        except Exception as e:
            logger.critical(f"应用程序启动失败: {e}")
            if self.app:
                QMessageBox.critical(
                    None,
                    "启动失败",
                    f"应用程序启动失败:\n{str(e)}\n\n请检查系统环境和依赖库。"
                )
            return 1

def main():
    """主函数"""
    try:
        # 创建并运行应用程序
        app = MySQLDictExporterApp()
        return app.run()
    except Exception as e:
        print(f"程序启动失败: {e}")
        return 1

if __name__ == "__main__":
    sys.exit(main())
